"""
Copyright (c) 2025 Huawei Technologies Co., Ltd.
This file is a part of the CANN Open Software.
Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
Please refer to the License for details. You may not use this file except in compliance with the License.
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON_INFRINGEMENT,
MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
See LICENSE in the root of the software repository for the full text of the License.
"""

import pandas as pd
import subprocess
import sys
import os
import time

def convert_seconds(seconds):
    hours = seconds // 3600
    remaining_seconds = seconds % 3600
    minutes = remaining_seconds // 60
    final_seconds = remaining_seconds % 60
    return hours, minutes, final_seconds

def run(deviceId, targetName):
    # pandas 读取csv
    data = pd.read_csv('./input_params/MNKC_data_prof.csv')

    input_header = data.columns.tolist()
    calc_header = ["cann_var_sequence_gemm_time_us", 
                    "cann_var_sequence_gemm_Tflops", 
                    "cann_var_sequence_gemm_speedup_rate", 
                    "cann_var_sequence_gemm_aic_total_hit_rate", 
                    "cann_var_sequence_gemm_aic_cube_ratio", 
                    "cann_var_sequence_gemm_aic_mte2_ratio", 
                    "cann_var_sequence_gemm_aic_fixpipe_ratio"]
    output_header = input_header + calc_header

    # 最后要写入的结果表格的表头
    results = pd.DataFrame(columns=output_header)
    prof_data_path = "./output_result/batch_prof_data.csv"

    run_profiling_format = "./run_profiling.sh {} {}" + len(input_header) * " {}"

    # 获取每行数据（不包含表头，只是在第0行写入的时候加上表头）
    for index, row in data.iterrows(): 
        
        input_list = row.tolist()
        command = run_profiling_format.format(deviceId, targetName, *input_list)
        result = subprocess.run(command, shell=True, capture_output=True, text=True)

        # prof.py最后一行输出需要的数据
        last_line1 = result.stdout.strip().splitlines()[-1]
        # 对最后一行切分得到数据（默认按照空格切分）
        calc_list = last_line1.split()[1::2]

        output_list = input_list + calc_list
        print("[", str(index+2), "]", end="")
        for i in range(len(output_header)):
            print(output_header[i], ":", output_list[i], end=";")
        print()

        frame =  pd.DataFrame([output_list], columns=output_header)
        if index == 0:
            frame.to_csv(prof_data_path, mode='w', header=True, index=False)
        else:
            frame.to_csv(prof_data_path, mode='a', header=not os.path.exists(prof_data_path), index=False)
   

if __name__ == "__main__":

    deviceId = int(sys.argv[1]) 
    targetName = sys.argv[2]

    start_time = time.time()

    print(f"Running {targetName} on device {deviceId}...\n")
    
    run(deviceId, targetName)

    end_time = time.time()
    elapsed_secs = end_time - start_time
    elapsed_hours, elaspsed_mins, elapsed_remained_secs = convert_seconds(elapsed_secs)
    print(f"\nRunning ${targetName} on device ${deviceId} finished Elapsed time: {elapsed_hours} hours, {elaspsed_mins} minutes, {elapsed_remained_secs} seconds. ")